//
//  AppDelegate.m
//  BangoiOSSDKTestApp
//
//  Created by Development Bango on 12/06/2013.
//  Copyright (c) 2013 Development Bango. All rights reserved.
//

#import "AppDelegate.h"
#import "BGOAnalyticsConstants.h"
#import "BGOAnalyticsManager.h"
#import "BangoConfigConstants.h"
#import "BGOTransmissionModeConstants.h"
#import "BGOSessionEventsConstants.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSLog(@"> %s", __PRETTY_FUNCTION__);
    // Override point for customization after application launch.
    //initialise Bango Analytics
    
    analytics_ = [BGOAnalyticsManager sharedManager];
    
    //set the exception handler
    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    //config options
    analytics_.findLocation = YES;
    analytics_.debugLog = YES;
    analytics_.applicationChannel = @"Direct to Device";
    analytics_.applicationType = @"Test app for analytics";
    analytics_.continueSessionSeconds = 10;
    analytics_.useIdentifierForVendor = YES;
    //analytics_.identifyBangoUser = YES;
    
    //set the logging level
    [analytics_ setEvents:[NSArray arrayWithObjects:EVENT_VIDEOSTART, EVENT_VIDEOSTOP, nil] forLogLevel:LEVEL_VIDEO];
    [analytics_ setEvents:[NSArray arrayWithObjects:EVENT_AUDIOSTART,EVENT_AUDIOSTOP, nil] forLogLevel:LEVEL_AUDIO];
    [analytics_ setEvents:[NSArray arrayWithObjects:EVENT_PAGEVIEW,EVENT_SEARCH, nil]      forLogLevel:LEVEL_PAGEVIEW_AND_SEARCH];
    
    //set the app ID
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        [[NSUserDefaults standardUserDefaults] setValue:BANGO_IPAD_APPLICATION_ID forKey:BANGO_APPLICATION_ID];
        
    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setValue:BANGO_IPHONE_APPLICATION_ID forKey:BANGO_APPLICATION_ID];
        // Running on iPhone or iPod touch
        
    }
    
    [analytics_ onStartSessionWithApplicationId:[[NSUserDefaults standardUserDefaults] objectForKey:BANGO_APPLICATION_ID]];

    NSLog(@"log %@",[[NSUserDefaults standardUserDefaults] objectForKey:BANGO_APPLICATION_ID]);
    
    
    return YES;

}

void uncaughtExceptionHandler(NSException *exception){
    BGOAnalyticsManager *analytics = [BGOAnalyticsManager sharedManager];
	
	NSMutableString *exceptionString = [NSMutableString stringWithString:@"name: "];
	[exceptionString appendString:exception.name];
	[exceptionString appendString:@" reason: "];
	[exceptionString appendString:exception.reason];
	
	NSNumber * errorLevel = [NSNumber numberWithInt:BGO_ERROR_INTERNAL_CRITICAL];
    
	[analytics onErrorWithEventParameters:nil message:exception.name eventClass:@"Uncaught Exception"
                          eventErrorLevel:errorLevel eventErrorId:exceptionString];
}
							
- (void)applicationWillResignActive:(UIApplication *)application
{
  
	
	/*
	 BGO_ANALYTICS_APPLICATION_WILL_RESIGN_ACTIVE_END
	 */
	

}
- (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}


- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    NSLog(@"> %s", __PRETTY_FUNCTION__);
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
	
	/*
	 BGO_ANALYTICS_APPLICATION_WILL_RESIGN_ACTIVE_START
	 */
	
    // Log Idle Event
    UIDevice * device = [UIDevice currentDevice];
    BOOL backgroundSupported = NO;
    if ([device respondsToSelector:@selector(isMultitaskingSupported)]) {
        backgroundSupported = device.multitaskingSupported;
    }
    
    if (backgroundSupported) {
        UIApplication * app = [UIApplication sharedApplication];
        
        backgroundTaskId_ = [app beginBackgroundTaskWithExpirationHandler:^{
            [app endBackgroundTask:backgroundTaskId_];
            backgroundTaskId_ = UIBackgroundTaskInvalid;
        }];
        
        // Start the long-running task and return immediately.
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            // Do the work associated with the task.
            // BGOAnalyticsManager *analytics = [BGOAnalyticsManager sharedManager];
			
			// If the user agent string is NIL then we've not initialised the user agent yet, which
			// means it is unsafe to invoke the Analytics Singleton from the resign active state
            
			if ([analytics_ userAgent] != nil)
            	[analytics_ onIdleWithEventParameters:nil
                                          eventDetail:@"applicationWillResignActive"
                                           eventValue:nil fromBackground:YES];
            
            [app endBackgroundTask:backgroundTaskId_];
            backgroundTaskId_ = UIBackgroundTaskInvalid;
        });
    } else {
		// No multitasking support so make a regular call to onIdle...
		//BGOAnalyticsManager *analytics = [BGOAnalyticsManager sharedManager];
		
        // If the user agent string is NIL then we've not initialised the user agent yet, which
        // means it is unsafe to invoke the Analytics Singleton from the resign active state
        
        if ([analytics_ userAgent] != nil)
            [analytics_ onIdleWithEventParameters:nil
                                      eventDetail:@"applicationWillResignActive"
                                       eventValue:nil];
		
	}
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [analytics_ onResumeWithEventParameters:nil eventDetail:@"applicationWillEnterForeground" eventValue:nil];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [analytics_ onEndSessionWithEventParameters:nil eventDetail:@"applicationWillTerminate" eventValue:nil];
}

+ (AppDelegate *) sharedAppDelegate{
    return (AppDelegate *) [UIApplication sharedApplication].delegate;
}

@end
